package com.schoolhelper.notification.mapper;

import com.schoolhelper.notification.domain.Notification;
import org.apache.ibatis.annotations.*;
import java.util.List;

/**
 * 通知数据访问层
 */
@Mapper
public interface NotificationMapper {
    
    /**
     * 插入新通知
     */
    @Insert("INSERT INTO notifications (user_id, type, title, content, is_read, related_id, related_user_id, create_time, update_time) " +
            "VALUES (#{userId}, #{type}, #{title}, #{content}, #{isRead}, #{relatedId}, #{relatedUserId}, #{createTime}, #{updateTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertNotification(Notification notification);
    
    /**
     * 根据用户ID获取通知列表
     */
    @Select("SELECT * FROM notifications WHERE user_id = #{userId} ORDER BY create_time DESC LIMIT #{limit} OFFSET #{offset}")
    List<Notification> findByUserId(@Param("userId") Long userId, @Param("limit") int limit, @Param("offset") int offset);
    
    /**
     * 获取用户未读通知数量
     */
    @Select("SELECT COUNT(*) FROM notifications WHERE user_id = #{userId} AND is_read = 0")
    int getUnreadCount(@Param("userId") Long userId);
    
    /**
     * 获取用户未读通知列表
     */
    @Select("SELECT * FROM notifications WHERE user_id = #{userId} AND is_read = 0 ORDER BY create_time DESC")
    List<Notification> findUnreadByUserId(@Param("userId") Long userId);
    
    /**
     * 标记通知为已读
     */
    @Update("UPDATE notifications SET is_read = 1, update_time = NOW() WHERE id = #{id}")
    int markAsRead(@Param("id") Long id);
    
    /**
     * 标记通知为已读（带用户权限验证）
     */
    @Update("UPDATE notifications SET is_read = 1, update_time = NOW() WHERE id = #{id} AND user_id = #{userId}")
    int markAsReadWithUserCheck(@Param("id") Long id, @Param("userId") Long userId);
    
    /**
     * 批量标记通知为已读
     */
    @Update("UPDATE notifications SET is_read = 1, update_time = NOW() WHERE user_id = #{userId} AND is_read = 0")
    int markAllAsRead(@Param("userId") Long userId);
    
    /**
     * 根据类型和相关ID获取通知
     */
    @Select("SELECT * FROM notifications WHERE user_id = #{userId} AND type = #{type} AND related_id = #{relatedId}")
    List<Notification> findByTypeAndRelatedId(@Param("userId") Long userId, @Param("type") String type, @Param("relatedId") Long relatedId);
    
    /**
     * 删除通知
     */
    @Delete("DELETE FROM notifications WHERE id = #{id}")
    int deleteNotification(@Param("id") Long id);
    
    /**
     * 根据用户ID删除所有通知
     */
    @Delete("DELETE FROM notifications WHERE user_id = #{userId}")
    int deleteByUserId(@Param("userId") Long userId);
}